import { existsSync, writeFileSync } from 'fs';
import { dirname, join } from "path";
import { IWriter, ITableOutput } from "../../inters/InterfaceApi";
import { mkdirsSync } from '../../utils/CpFile';
import { newLine } from '../utils/ClsFactory';
import { codeMgr } from '../mgr/CodeMgr';

export class TsWriter implements IWriter {

    private _cfg: ITableOutput;

    write(data: any, options?: any, callback?: (res?: any) => void) {
        this._cfg = data;

        // let path = options.path;

        let dts = "";
        let exportDtsName = "";
        let clsHash = {};

        codeMgr.dtsList.forEach(ts => {
            if (clsHash[ts.name]) return;
            dts += ts.toString() + newLine + newLine;
            dts = dts.replace(/\?\:int/g, "?:number");
            dts = dts.replace(/\?\:long/g, "?:number");
            dts = dts.replace(/\?\:float/g, "?:number");
            dts = dts.replace(/\?\:double/g, "?:number");
            dts = dts.replace(/\?\:bool/g, "?:boolean");
            if (exportDtsName !== "") {
                exportDtsName += ",";
            }
            exportDtsName += ts.name;
            clsHash[ts.name] = 1;
        })
        let opPath: string[]
        if (typeof this._cfg.path == 'string') {
            opPath = [this._cfg.path];
        } else {
            opPath = this._cfg.path
        }
        // let path = options.path;
        opPath.forEach(p => {
            let dir = p;//join(path, p);
            if (!existsSync(dir)) {
                mkdirsSync(dir);
            }
            let str = dts + newLine + "export {" + exportDtsName + "}";

            writeFileSync(join(dir, `${this._cfg.fileName}.${this._cfg.type}`), str);
        })

        if (!!callback) callback();
    }

}